'use strict';

import cryptoFramework from '@ohos.security.cryptoFramework';
import buffer from '@ohos.buffer';
import { LogUtil } from '../utils/log-util'

const algNames = ['SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512', 'MD5', 'SM3'];

const Encryptor = {
    hash(algorithm, ...buffers) {
        const hash = cryptoFramework.createMd(algorithm);
        let dataBlob = { data: new Uint8Array(buffer.concat(buffers)) }
        hash.updateSync(dataBlob);
        let mdOutput = hash.digestSync();
        return buffer.from(mdOutput.data);
    },

    //note：在openHarmony上加上spinCount次数会导致appcrash
    convertPasswordToHash(password, hashAlgorithm, saltValue, spinCount) {

        if (algNames.indexOf(hashAlgorithm) < 0) {
            throw new Error(`Hash algorithm '${hashAlgorithm}' not supported!`);
        }

        // Password must be in unicode buffer
        const passwordBuffer = buffer.from(password, 'utf16le');
        // Generate the initial hash
        let key = this.hash(hashAlgorithm, buffer.from(saltValue, 'base64'), passwordBuffer);
        // Now regenerate until spin count
        return key.toString('base64');
    },

    /**
     * Generates cryptographically strong pseudo-random data.
     * @param size The size argument is a number indicating the number of bytes to generate.
     */
    randomBytes(size) {
        let result = new ArrayBuffer(0);
        let rand = cryptoFramework.createRandom();
        try {
            let randData = rand.generateRandomSync(size);
            if (randData != null) {
                result = buffer.from(randData.data);
            }
        } catch (error) {
            LogUtil.error(`randomBytes error`);
        }
        return result;
    }
};

export default Encryptor;
